package com.zimmur.app.mocolink.background.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.zimmur.app.mocolink.background.common.ReturnJsonEntity;
import com.zimmur.app.mocolink.background.common.StatusCodeEnum;
import com.zimmur.app.mocolink.background.fdfs.FileContentTypeUtil;
import com.zimmur.app.mocolink.domain.model.AppVersion;
import com.zimmur.app.mocolink.domain.model.StorageFiles;
import com.zimmur.app.mocolink.domain.util.DateUtils;
import com.zimmur.app.mocolink.domain.util.StringUtils;
import com.zimmur.app.mocolink.domain.vo.AppVersionInfo;
import com.zimmur.app.mocolink.service.IAppVersionService;
import com.zimmur.app.mocolink.service.IStorageFilesService;


@RestController
@RequestMapping("/restful/system")
public class SystemController extends BaseController{
	private static final Logger log = LoggerFactory.getLogger(SystemController.class);
	@Autowired
	private IAppVersionService appVersionService;
	@Autowired
	private IStorageFilesService storageFilesService;
	/**
	 * Android版本升级检查
	 * @return
	 */
	@RequestMapping(value="/checkupgrade",method=RequestMethod.GET)
	public ReturnJsonEntity checkVersion(){
		ReturnJsonEntity entity = new ReturnJsonEntity();
		StatusCodeEnum status = StatusCodeEnum.CODE100000;
		entity.setMsg("当前已经是最新版本!");
		Integer versionNo = getParam("versionNo", 0);
		try {
			AppVersion appVersion = appVersionService.selectNew();
			if(appVersion!=null && appVersion.getId()>versionNo){
				AppVersionInfo versionInfo = new AppVersionInfo();
				versionInfo.setVersionNo(appVersion.getId());
				versionInfo.setContent(appVersion.getContent());
				versionInfo.setAppVersion(appVersion.getAppVersion());
				versionInfo.setFileSize(appVersion.getFileSize());
				versionInfo.setCreateDate(DateUtils.dateFormat(appVersion.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
				status = StatusCodeEnum.CODE000000;
				entity.setMsg("新版本升级");
				entity.setData(versionInfo);
			}
		}catch (Exception er) {
			log.error(er.getMessage());
			status = StatusCodeEnum.CODE100000;
			entity.setData(new HashMap<>());
			entity.setMsg("当前已经是最新版本!");
			
		}
		entity.setCode(status.getCode());
		return entity;
	}
	/**
	 * Android版本升级
	 */
	@RequestMapping("/versionupgrade")
	public ReturnJsonEntity androidUpgrade(){
		ReturnJsonEntity entity = new ReturnJsonEntity();
		StatusCodeEnum status = StatusCodeEnum.CODE100000;
		Integer versionNo = getParam("versionNo", 0);
		try {
			AppVersion appVersion =appVersionService.selectById(versionNo);
			if(appVersion!=null && !StringUtils.isBlank(appVersion.getFileUrl())){
				status = StatusCodeEnum.CODE000000;
				String path = getRequest().getServletContext().getRealPath("/");//得到当前应用在服务器的绝对路径
				FileInputStream in = new FileInputStream(path+appVersion.getFileUrl());
				if(in!=null){
					long fileLength = appVersion.getFileSize();
					HttpServletResponse response = getResponse();
					response.setContentType(FileContentTypeUtil.getcontentType("apk"));  
					response.setHeader("Content-disposition", "attachment; filename=mocolink-"+appVersion.getAppVersion()+".apk");  
					response.setHeader("Content-Length", String.valueOf(fileLength));  
					
					//BufferedInputStream bis = null;
					BufferedOutputStream bos = null;
					try {
						//bis = new BufferedInputStream(in);
						bos = new BufferedOutputStream(getResponse().getOutputStream());  
						byte[] buff = new byte[2048];  
						int bytesRead;  
						while (-1 != (bytesRead = in.read(buff, 0, buff.length))) {  
							bos.write(buff, 0, bytesRead);  
						}  
						in.close();
					} catch (Exception e) {
						log.error(e.getMessage());
					}finally{
						if(in != null){
							in.close();
						}
						try {
							if(bos != null)
								bos.close();
						} catch (IOException e) {
							e.printStackTrace();
						}  
					}
				}
			}
		}catch (Exception er) {
			log.error(er.getMessage(),er);
			status = StatusCodeEnum.CODE100000;
			entity.setData(new HashMap<>());
			
		}
		entity.setCode(status.getCode());
		entity.setMsg(status.getMsg());
		return entity;
	}
}
